package org.base.common.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import org.base.common.holder.TimeZoneOffsetHolder;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

/**
 * @author He mingliang
 * @date 2020/5/9
 */
public class LocalDateTimeDeserializer extends com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer {

    public LocalDateTimeDeserializer(DateTimeFormatter formatter) {
        super(formatter);
    }

    protected LocalDateTimeDeserializer(com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer base, Boolean leniency) {
        super(base, leniency);
    }

    @Override
    protected com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer withDateFormat(DateTimeFormatter formatter) {
        return new LocalDateTimeDeserializer(formatter);
    }

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        LocalDateTime localDateTime = super.deserialize(parser, context);
        if (localDateTime != null) {
            final Integer offset = TimeZoneOffsetHolder.getOffset();
            if (offset != null && offset > 0) {
                localDateTime = localDateTime.minus(offset, ChronoUnit.HOURS);
            }
        }
        return localDateTime;
    }
}
